package com.company.project.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.company.project.common.exception.BusinessException;
import com.company.project.common.exception.code.BaseResponseCode;
import com.company.project.common.utils.DateUtils;
import com.company.project.common.utils.Sign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.company.project.mapper.SysFileMapper;
import com.company.project.entity.SysFileEntity;
import com.company.project.service.SysFileService;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;


@Service("sysFileService")
@Slf4j
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFileEntity> implements SysFileService {

    @Value("${web.upload-root}")
    private String uploadRootPath;
    @Value("${web.upload-file}")
    private String uploadFilePath;

    @Override
    public SysFileEntity uploadFile(MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        SysFileEntity sysFileEntity = new SysFileEntity();
//        try {
        String oldName = uploadFile.getOriginalFilename();
            String path = new String(uploadRootPath + uploadFilePath);
            String format = DateUtils.format(new Date(), "yyyy/MM/dd/");
            File file = new File(path + format);
            log.info("-----------存放上传文件的文件夹【" + file + "】-----------");
            log.info("-----------输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径【" + file.getAbsolutePath() + "】-----------");
            if (!file.isDirectory()) {
                //递归生成文件夹
                file.mkdirs();
            }
            log.info("-----------文件原始的名字【" + oldName + "】-----------");

            String suffix = oldName.substring(oldName.lastIndexOf("."), oldName.length());
//            String uuid = UUID.randomUUID().toString();
            String uuid = null;
            uuid = Sign.encodeFile(uploadFile.getBytes());
            String newName = uuid + suffix;
            log.info("-----------文件要保存后的新名字【" + newName + "】-----------");
            //构建真实的文件路径
            File newFile = new File(file.getAbsolutePath() + File.separator + newName);

            String webPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String filePath = "/" + uploadFilePath + "/" + format + newName;

            sysFileEntity.setId(uuid);
            sysFileEntity.setName(oldName);
            sysFileEntity.setUrl(filePath);
            sysFileEntity.setSuffix(suffix);
            sysFileEntity.setCreateTime(new Date());
            // 插入数据库

            SysFileEntity fileEntity = this.getById(uuid);
            if (null == fileEntity) {
                boolean saveFlag = this.save(sysFileEntity);
                log.info("插入数据库状态 = " + saveFlag);
                if (!saveFlag) {
                    new BusinessException(BaseResponseCode.DATA_BASE_ERROR);
                }
            } else {
                sysFileEntity = fileEntity;
            }
            //转存文件到指定路径，如果文件名重复的话，将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
            try {
                uploadFile.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("-----------【" + webPath + filePath + "】-----------");
//        } catch (IOException e) {
//            new BusinessException(BaseResponseCode.SYSTEM_BUSY);
//        }
        return sysFileEntity;
    }

    @Override
    public void resSterm(String id, HttpServletResponse response) throws IOException {
        // 查询id 图片
        SysFileEntity sysFileEntity = this.getById(id);
        String fileUrl = sysFileEntity.getUrl();
        String suffix = sysFileEntity.getSuffix();
        OutputStream os = null;
        try {
            BufferedImage image = ImageIO.read(new FileInputStream(new File(uploadRootPath+fileUrl)));
            response.setContentType("image/" + suffix.replace(".",""));
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, suffix.replace(".",""), os);
            }
        } catch (IOException e) {
            new BusinessException(BaseResponseCode.OPERATION_ERRO.getCode(), e.getMessage());
        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
    }
}